
/** The class include methods which format/convert a string.
    The methods include
        * Convert between a phone number (int) and string.
        * Remove/add leading trailing spaces.
        * Remove extra spaces.
        * Convert between string and tokens.
*/
import java.io.*;
import java.sql.*;
import java.text.*;
 
public class ScreenIO {
 
     public static int stringToInt(String s) {
        int i, j, k =s.trim().length() ;
        if ( k==0 ) return 0;
        char c, t[] = new char[k];
        for ( i=0, j=0; j < k ; j++) {
                c = s.charAt(j) ;
                if ( c >= '0' && c <= '9' ) t[i++] = c;
        }
        return Integer.parseInt( new String(t, 0, i));
      }
 
 
     public static long stringToLong(String s) {
        int i, j, k =s.trim().length() ;
        if ( k == 0 ) return 0L;
        char c, t[] = new char[k];
        for ( i=0, j=0; j < k ; j++) {
                c = s.charAt(j) ;
                if ( c >= '0' && c <= '9' ) t[i++] = c;
        }
        return Long.parseLong( new String(t, 0, i));
      }
 
// ----------------------------------------------------------------
//   Expand string by padding a char string or space.
// ----------------------------------------------------------------
     public static String makeString(char c, int len) {
        char buf[] = new char[len];
        for ( int i = 0; i < len; i++ ) buf[i] = c;
        String t = new String(buf);
        return t;
     }
 
     public static String space(int len) {
        return makeString(' ', len);
     }
 
// ----------------------------------------------------------------
//   Expand string by padding spaces to the right of string.
// ----------------------------------------------------------------
     public static String expandString(String s, int len) {
        int origLen = 0;
        if (s == null )  s = "";  else origLen = s.length();
        if ( origLen >= len ) return s.substring(0, len);
        else  return s + makeString(' ', len - origLen);
     }
 
// ----------------------------------------------------------------
//   Expand string by padding spaces to the left of string.
// ----------------------------------------------------------------
     public static String expandString(int len, String s) {
        int origLen = 0;
        if (s == null ) s = "";  else origLen = s.length();
        if ( origLen >= len ) return s.substring(0, len);
        else  return  makeString(' ', len - origLen) + s;
     }
 
     public static String capitalize(String s) {
        if ( s == null ) return s;
        return s.substring(0,1).toUpperCase() + s.substring(1, s.length()).toLowerCase();
     }
 
     public static String escapeDoubleQuotes(String s) {
        String t = "";
        int start =0, k = s.indexOf('\"');
        while ( k >= 0 ) {
                t = t + s.substring(0, k) + "\\\"";
                s = s.substring(k+1, s.length());
                k = s.indexOf('\"');
        }
        return t + s;
     }
 
     public static String removeExtraBlanks (String s) {
        s = s.trim();
        int idx1 = 0, idx2 = 0, len =s.length() ;
        char c, t[] = new char[len];
 
        boolean spaceBefore = false;
 
        for ( idx1=0, idx2=0; idx1 < len ; idx1++) {
                c = s.charAt(idx1) ;
                if (c == ' ' || c == '\t' || c == '\n') {
                        if ( !spaceBefore ) {
                                t[idx2++] = c;
                                spaceBefore = true; }
                } else {
                        t[idx2++] = c;
                        spaceBefore = false;
                  }
        }
        return new String(t, 0, idx2) ;
      }
 
      public static String formatPhone(long ph) {
        if ( ph == 0 ) return "";
        String s0 = "", s1, s2;
        long cd = ph;
        if ( ph >= 10000000 ) {
                cd = ph / 10000000;
                s0 = cd>=100? cd+"-": cd>=10 ? "0"+cd+"-": "00"+cd+"-";
                ph = ph % 10000000;
        }
        cd = ph/10000;
        s1= cd>=100? cd+"-": cd>=10 ? "0"+cd+"-": "00"+cd+"-";
        cd = ph%10000;
        s2 = cd>=1000? cd+"": cd>=100 ? "0"+cd: cd>=10 ? "00"+cd : "000"+cd ;
        return s0+s1+s2 ;
      }
 
      public static String formatSSN(long ssn) {
        if ( ssn == 0 ) return "";
        String s[] = new String[3];
        int    lens[] = { 3, 2, 4 };
        s[0] = ""+ ssn / 1000000;  s[1]= ssn % 1000000 / 10000 + ""; s[2] =""+ssn%10000;
        for ( int i = 0; i < 3; i ++ )
             if ( s[i].length() < lens[i] )
                s[i] = makeString('0', lens[i] - s[i].length()) + s[i];
        return s[0] + '-' + s[1] + '-' + s[2];
      }
 
      public static String formatDouble(double d, int prec) {
        String fmt = makeString('0', prec);
        DecimalFormat df = new DecimalFormat("#,##0." + fmt);
        StringBuffer   res = new StringBuffer();
        df.format(d, res, new FieldPosition(prec));
        return new String(res);
      }
 
      public static String formatFloat( float f, int prec ) { return formatDouble ( (double) f, prec ) ; }
 
        // all float, double are truncated, not rounded.
      public static String formatCurrency( double d) { return '$' + formatDouble ( d,  2) ; }
      public static String formatCurrency( float f) { return '$' + formatDouble( (double) f, 2) ; }
      public static String formatCurrency( double d, int prec ) { return '$' + formatDouble ( d, prec ) ; }
      public static String formatCurrency( float f, int prec ) { return '$' + formatDouble ( (double) f, prec ) ; }
 
      public static String formatInt( int i ) { return formatLong( (long) i ) ;
}
 
      public static String formatLong(long d) {
        DecimalFormat df = new DecimalFormat("#,###");
        StringBuffer   res = new StringBuffer();
        df.format(d, res, new FieldPosition(0));
        return new String(res);
      }
 
// ----------------------------------------------------------------
//   Prompt for continuation of listing.
// ----------------------------------------------------------------
      public static boolean continueToList() {
        byte ans[] = new byte[10]; char c = ' ';
        System.out.print("\nPress Q/q to quit, any other key to continue listing ... ");
        try { System.in.read(ans); } catch (IOException e) {return true;}
        try { c = (new String(ans)).trim().charAt(0); }
        catch (StringIndexOutOfBoundsException e) { return true;}
        if ( c == 'Q' || c == 'q' ) return false;
        return true;
     }
 
// ----------------------------------------------------------------
//   Print a prompt message for input data.
// ----------------------------------------------------------------
     public static String promptForString( String prompt ) {
        byte ans[] = new byte[120];
        System.out.print(prompt);
        try { System.in.read(ans); } catch (IOException e) { return null; }
        return (new String(ans)).trim();
     }
 
     public static char promptForChar( String prompt ) {
        byte ans[] = new byte[120]; char c;
        System.out.print(prompt);
        try { System.in.read(ans); } catch (IOException e) { return ' '; }
        try { c = (new String(ans)).trim().charAt(0); }
        catch (StringIndexOutOfBoundsException e) { return ' '; }
        return c;
     }
 
     public static int promptForInt( String prompt ) {
        byte ans[] = new byte[120];
        System.out.print(prompt);
        try { System.in.read(ans); } catch (IOException e) { return 0; }
        return Integer.parseInt((new String(ans)).trim());
     }
 
// ----------------------------------------------------------------
//   Print a menu passed as an array of strings.
// ----------------------------------------------------------------
     public static void showMenu( String menu[] ) {
        System.out.println();
        for ( int i = 0; i <  menu.length; i ++ )
                System.out.println(menu[i]);
        System.out.println();
     }
 
     public static void showMenu(String linePrefix, String menu[] ) {
        System.out.println();
        for ( int i = 0; i <  menu.length; i ++ )
                System.out.println( linePrefix + menu[i]);
        System.out.println();
     }
 
// ----------------------------------------------------------------
//   Display a result on screen.
// ----------------------------------------------------------------
    public static void displayResultSet(ResultSet res ) {
        int widthArr[] = null;
        ResultSetMetaData meta;
        try {
                meta = res.getMetaData();
                int colCnt = meta.getColumnCount();
                widthArr = getColumnWidths(colCnt, meta);
                displayColumnHeaders(colCnt, widthArr, meta);
                int rowCount = 0;
 
                while ( res.next() ) {
                        for ( int i = 1; i <= colCnt; i ++ )
                                System.out.print(ScreenIO.expandString( res.getString(i), widthArr[i-1] + 1)) ;
                        System.out.println();
                        if ( ++rowCount % 20 == 0 && ! ScreenIO.continueToList() ) return;
                }
        } catch (SQLException e) { e.printStackTrace();  /*System.exit(-1);*/ }
             catch (NullPointerException e ) {}
    }
 
    static void displayColumnHeaders(int cnt, int [] widthArr, ResultSetMetaData meta) {
        try {
                for ( int i = 1; i <= cnt; i ++ )
                        System.out.print( ScreenIO.expandString(meta.getColumnName(i), widthArr[i-1] + 1));
                System.out.println();
 
                for ( int i = 1; i <= cnt; i ++ )
                        System.out.print( ScreenIO.makeString('=', widthArr[i-1]) + ' ');
                System.out.println();
        } catch (SQLException e ) {}
 
    }
 
    static int [] getColumnWidths(int colCnt, ResultSetMetaData meta) {
        int [] widthArr = new int[colCnt];
        for ( int i = 1; i <= colCnt; i ++ ) {
           try {
                widthArr[i-1] = meta.getColumnDisplaySize(i);
                switch( meta.getColumnType(i) ) {
                   case Types.NUMERIC: widthArr[i-1] = 10; break;
                   case Types.DECIMAL: widthArr[i-1] = 10; break;
                   case Types.DATE: widthArr[i-1] = 10; break;
                   case Types.TIME: widthArr[i-1] = 10; break;
                   case Types.TIMESTAMP: widthArr[i-1] = 10; break;
                }
            } catch (SQLException e) {}
        }
        return widthArr;
    }
// -------------- End of displayResultSet ---------------------------------------------
}

